package com.ssy.lingxi.message.websocket.config;

import com.ssy.lingxi.message.serviceimpl.InSiteMessageService;
import com.ssy.lingxi.message.websocket.session.WsSessionContext;
import com.ssy.lingxi.message.websocket.session.WsSessionKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * webSocket处理器
 * @author yzc
 * @version 2.0.0
 * @date 2020/11/2
 */
@Slf4j
public class SimpleWebSocketHandler extends TextWebSocketHandler {

    private final InSiteMessageService inSiteMessageService;

    public SimpleWebSocketHandler(InSiteMessageService inSiteMessageService) {
        this.inSiteMessageService = inSiteMessageService;
    }

    /**
     * open事件
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        WsSessionKey wsSessionKey = WsSessionKey.generate(session);

        this.printLog(wsSessionKey, "连接成功", "success");

        // 保存session
        WsSessionContext.add(wsSessionKey.toString(), session);

        Integer source = Integer.valueOf(wsSessionKey.getSource());
        Long memberId = Long.valueOf(wsSessionKey.getMemberId());
        Long roleId = Long.valueOf(wsSessionKey.getRoleId());
        Long userId = Long.valueOf(wsSessionKey.getUserId());

        // 查询未读消息数量
        inSiteMessageService.countUnreadMessageCount(source, memberId, roleId, userId);
    }

    /**
     * onMessage事件
     * @param session
     * @param textMessage
     * @throws Exception
     */
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage textMessage) {
        WsSessionKey wsSessionKey = WsSessionKey.generate(session);
        this.printLog(wsSessionKey, "接收消息", textMessage);
    }

    /**
     * close事件
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        WsSessionKey wsSessionKey = WsSessionKey.generate(session);
        this.printLog(wsSessionKey, "连接关闭", status);
        WsSessionContext.remove(session);
    }

    /**
     * error事件
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        WsSessionKey wsSessionKey = WsSessionKey.generate(session);
        this.printLog(wsSessionKey, "发生异常", exception);
    }

    private void printLog(WsSessionKey wsSessionKey, String operation, Object operationMsg) {
        log.info("source: {}, member: {}, roleId: {}, userId: {}, {}: {}", wsSessionKey.getSource(), wsSessionKey.getMemberId(), wsSessionKey.getRoleId(), wsSessionKey.getUserId(), operation, operationMsg);
    }
}